<?php

namespace App\Http\Controllers;

use App\Exceptions\PhonicsWithdrawFinishedException;
use App\Exceptions\PhonicsWithdrawNotFoundException;
use App\Facades\WxMerchantTransfer;
use App\Models\PhonicsStudent;
use App\Models\PhonicsWithdraw;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AdminPhonicsWithdrawController extends Controller
{

    public function manage(Request $request)
    {
        $this->validate($request, [
            "studentId" => "integer|min:1",
            "page" => "integer|min:1",
            "pageSize" => "integer|max:100|min:5",
            "status" => "integer|in:0,1,2"
        ]);

        $query = PhonicsWithdraw::query();
        if ($request->has("studentId")) {
            $query->where("student_id", intval($request->input("studentId")));
        }
        if ($request->has('status')) {
            $query->where('status', intval($request->input('status')));
        }

        $total = $query->count();
        $page = intval($request->input("page", 1));
        $pageSize = intval($request->input("pageSize", 10));
        $withdraws = $query->skip($pageSize * ($page - 1))->take($pageSize)->get();
        $result = [];
        foreach ($withdraws as $withdraw) {
            $result[] = [
                'id' => $withdraw->getId(),
                'amount' => floatval($withdraw->getAmount()),
                'studentId' => $withdraw->getStudentId(),
                'status' => $withdraw->getStatus(),
                'createdAt' => $withdraw->getCreatedAt()->getTimestamp(),
                'errorCode' => $withdraw->getErrorCode(),
                'errorMessage' => $withdraw->getErrorMessage(),
            ];
        }

        return new JsonResponse([
            "total" => $total,
            "page" => $page,
            "pageSize" => $pageSize,
            "result" => $result,
        ]);
    }

    public function confirm(Request $request, $id)
    {
        $request->merge(['id' => $id]);
        $this->validate($request, [
            'id' => 'required|integer'
        ]);

        $id = intval($id);
        $withdraw = PhonicsWithdraw::find($id);

        if (empty($withdraw)) {
            throw new PhonicsWithdrawNotFoundException();
        }

        if ($withdraw->getStatus() == PhonicsWithdraw::STATUS_FINISHED) {
            throw new PhonicsWithdrawFinishedException();
        }

        if (is_array($_SERVER) && array_key_exists('HTTP_REMOTEIP', $_SERVER)) {
            $clientIp = $_SERVER['HTTP_REMOTEIP'];
        } else {
            $clientIp = '192.168.0.1';  // fake client ip
        }

        $result = WxMerchantTransfer::transfer($withdraw->getAmount() * 100, $withdraw->getOpenId(), $withdraw->getId(), $clientIp);

        if ($result["result_code"] == "SUCCESS") {
            $withdraw->setStatus(PhonicsWithdraw::STATUS_FINISHED);
            $withdraw->setErrorCode("");
            $withdraw->setErrorMessage("");
            $withdraw->save();

            return new JsonResponse();
        } else {
            $withdraw->setStatus(PhonicsWithdraw::STATUS_ERROR);
            $withdraw->setErrorCode($result["err_code"]);
            $withdraw->setErrorMessage($result["err_code_des"]);
            $withdraw->save();

            Log::error('Error transfer withdraw: '. json_encode($result));

            return new JsonResponse("Error transfer to user", 400);
        }
    }

    public function retrieveTransfer(Request $request, $id)
    {
        $request->merge(['id' => $id]);
        $this->validate($request, [
            'id' => 'required|integer'
        ]);

        $id = intval($id);
        $withdraw = PhonicsWithdraw::find($id);

        if (empty($withdraw)) {
            throw new PhonicsWithdrawNotFoundException();
        }

        $result = WxMerchantTransfer::getTransferResult($id);

        return new JsonResponse(json_encode($result));
    }
}
